<template>
  <div class="com-map-select">
    <div class="com-map-content">
      <div class="com-map--head">
        <div class="ht">{{value.title}}</div>
        <a class="btn-close"
           href="javascript:void(0)"
           @click="close"><img src="static/img/icon/close.png"
               alt=""></a>
      </div>
      <div class="com-map--wrap">
        <div class="map-area-list">
          <div class="service-content">
            <div class="list-block">
              <ul>
                <li v-for="(item,index) in masData"
                    :key="'key-'+index">
                  <a href="javascript:void(0)"
                     @click="getToPoint(index)"
                     class="item-link item-content"
                     :class="{on:selected==index}">
                    <div class="item-inner">
                      <div class="item-title">
                        <div class="ht">
                          <span>{{index+1}}</span>
                          <strong>{{item.name}}</strong>
                        </div>
                        <p>地址：{{item.address}}
                          <br> 电话：{{item.tell}}
                        </p>
                      </div>
                    </div>
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div id="com-map-container"></div>
      </div>

    </div>
    <div class="mask"
         @click="close"></div>
  </div>
</template>
<script>
function getDistanceSortList (arr) {
  return arr.sort((a, b) => {
    return a.distance - b.distance
  })
}
function TMap (key) {
  return new Promise(function (resolve, reject) {
    window.init = function () {
      resolve(window.qq) // 注意这里
    }
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src =
      'https://map.qq.com/api/js?v=2.exp&libraries=geometry&callback=init&key=' +
      key
    script.onerror = reject
    document.head.appendChild(script)
  })
}

export default {
  props: ['value'], // title: '选择服务点', show: true, zoom: 16, map_center: [25.033481, 102.710082], url: '/pufa/api/organization/?org_type=2&code=530102', selected: ''
  data () {
    return {
      has_center: false,
      map_center: [],
      masData: [],
      markers_array: [],
      qq: '',
      map: '',
      infoWin: '',
      selected: ''
    }
  },
  methods: {
    close () {
      this.value.show = false
      this.$emit('input', this.value)
    },
    // 跳到地图点，并显示改点信息
    getToPoint (index) {
      const _this = this
      const item = this.masData[index]
      const [lan, lng] = item.geography.split(',')
      const position = new this.qq.maps.LatLng(lan, lng)
      this.showlist = false
      this.selected = index
      this.infoWin.open()
      this.infoWin.setContent(this.setMapContent(item))
      this.infoWin.setPosition(position)
      this.map.panTo(position)
      setTimeout(() => {
        const doms = document.querySelector('.map-choose-item')
        doms.addEventListener('click', function () {
          _this.value.selected = { ...this.dataset }
          _this.close()
        })
      }, 500)
    },
    // 设置地图点信息模版
    setMapContent (item) {
      const { name, address, tell, id } = item
      return `<div class="map-marker-info" style="padding:0 0 10px;">
          <h2 style="font-size:18px; margin:0 0 10px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">${name}</h2>
          <div style="color:#808080; font-size:16px;">
            <strong>地址：</strong>${address} <br>
            <strong>电话：</strong>${tell}<br>
          </div>
          <div style="padding:10px 0 0; margin-top:10px; border-top:1px solid #ddd;"><a href="javascript:void(0)" class="btn btn-danger map-choose-item" data-id="${id}" data-name="${name}">选择该服务点</a></div>
        </div>`
    },
    // 初始化地图点
    async init (requestURL) {
      // 获取api
      const { items } = await this.$get(requestURL)
      // 判断是否取得用户位置
      // console.log(userLocation)
      // let userPosition = true
      // if (userLocation && userLocation[0]) {
      //   const { lat, lng } = userLocation[1]
      //   this.map_center = [lat, lng]
      //   userPosition = true
      // }
      // 设置地图
      const dom = document.querySelector('#com-map-container')
      if (dom.childNodes.length) {
        dom.childNodes[0].remove()
      }

      if (this.value.map_center) {
        this.has_center = true
      }
      this.map_center = this.value.map_center || items[0].geography.split(',')
      // 在此完成该函数
      const qq = await TMap('OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77')
      const map = new qq.maps.Map(dom, {
        center: new qq.maps.LatLng(...this.map_center),
        zoom: this.value.zoom
      })
      // 地图点信息
      const infoWin = new qq.maps.InfoWindow({ map, zIndex: 10000 })
      // 存储地图对象
      this.qq = qq
      this.map = map
      this.infoWin = infoWin
      // 是否获取用户信息，获取了则计算距离
      this.masData = this.has_center ? this.getDistanceList(items) : items
      // 跳到的一个地图点中心，并打开信息
      this.getToPoint(0)
      const masData = this.masData
      this.markers_array = []
      // let { qq, map, infoWin } = this
      for (let i = 0; i < masData.length; i++) {
        const { geography } = masData[i]
        const [lan, lng] = geography.split(',')
        const position = new qq.maps.LatLng(lan, lng)
        const anchor = new qq.maps.Point(24, 50)
        const size = new qq.maps.Size(100, 100)
        const origin = new qq.maps.Point(0, 0)
        const scaleSize = new qq.maps.Size(48, 48)
        const icon = new qq.maps.MarkerImage(
          '/static/web/theme/gov_base_terminal/img/icon/position.png',
          size,
          origin,
          anchor,
          scaleSize
        )
        // 添加marker
        const marker = new qq.maps.Marker({
          position,
          map,
          animation: qq.maps.MarkerAnimation.DOWN
        })
        const infotmp = this.setMapContent(masData[i])
        // 加载marker图标
        marker.setIcon(icon)
        this.markers_array.push(marker)
        // 添加点击事件
        qq.maps.event.addListener(marker, 'click', () => {
          infoWin.open()
          infoWin.setContent(infotmp)
          infoWin.setPosition(position)
        })
      }

      // 拖动地图后事件
      qq.maps.event.addListener(map, 'dragend', event => infoWin.close())

      // await this.$delay(2000, 1000)
      // this.showlist = true
    },
    // 距离列表排讯
    getComputeList (arr) {
      let masdata = []
      getDistanceSortList(arr)
      arr.map(v => {
        let d =
          v.distance > 1000
            ? `（距离${(v.distance / 1000).toFixed(2)}公里）`
            : `（距离${parseInt(v.distance.toFixed(2))}米）`
        v.address += d
        masdata.push(v)
      })
      return masdata
    },
    // 计算距离列表
    getDistanceList (list) {
      const arr = []
      const [lat, lng] = this.map_center
      const qq = this.qq
      list.map((v, i) => {
        if (!v.geography) return
        let p = v.geography.split(',')
        let d = qq.maps.geometry.spherical.computeDistanceBetween(
          new qq.maps.LatLng(lat, lng),
          new qq.maps.LatLng(p[0], p[1])
        )
        v.distance = d
        arr.push(v)
      })
      return this.getComputeList(arr)
    }
  },
  async mounted () {
    const dom = document.querySelector('body')
    dom.style.overflowY = 'hidden'

    await this.init(this.value.url)
  },
  destroyed () {
    const dom = document.querySelector('body')
    dom.style.overflowY = 'auto'
  }
}
</script>

<style lang="scss">
.com-map-select {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 1000;
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  .com-map-content {
    height: 75%;
    width: 80%;
    background: #fff;
    border-radius: 10px;
    overflow: hidden;
    position: relative;
    z-index: 1100;
    .com-map--head {
      background: #fff;
      height: 80px;
      line-height: 80px;
      border-bottom: 1px solid #ccc;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .ht {
        font-size: 24px;
        margin-left: 20px;
      }
      .btn-close {
        opacity: 0.75;
        transition: opacity 0.3s ease-in-out;
        margin-right: 20px;
        &:hover {
          opacity: 1;
        }
      }
    }
    .com-map--wrap {
      display: flex;
      height: 100%;
      .map-area-list {
        width: 30%;
        overflow-y: scroll;
        box-shadow: 5px 0 5px rgba(0, 0, 0, 0.1);
        position: relative;
        z-index: 10000;
      }
    }
  }
  .mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    background: rgba(0, 0, 0, 0.5);
  }
}
#com-map-container {
  width: 100%;
  height: 100%;
}

.service-content {
  background: #fff;
  position: relative;

  .list-block {
    margin: 0 0 75px;
    ul {
      padding: 0;
      list-style: none;
    }
    .item-content {
      display: block;
      border-top: 1px solid #ddd !important;
      &.on {
        background: #eee;
      }
      &:active {
        background: #eee;
      }
    }
    .item-inner {
      padding: 15px;
    }
    .item-title {
      white-space: normal;
      .ht {
        font-weight: normal;
        display: block;
        padding-bottom: 5px;
        display: flex;
        align-items: center;
        span {
          width: 36px;
          height: 43px;
          line-height: 36px;
          display: block;
          margin-right: 5px;
          background-image: url('https://ynterminal.laway.cn/static/img/icon/map.png');
          background-size: 36px 43px;
          text-align: center;
          color: #fff;
          font-size: 18px;
          flex-shrink: 0;
        }
        strong {
          width: auto;
          font-size: 18px;
        }
      }
      p {
        color: #999;
        margin: 0;
        font-size: 16px;
      }
    }
  }
}
</style>
